
import os
import requests
import json
import os
from urllib.parse import urlparse, parse_qs
from moviepy.editor import *
def create_video_from_images_and_audio(audio_path, image_info, output_path):
    """
    创建一个视频，将给定的音频文件和图片按指定时间合成。

    :param audio_path: MP3文件的路径
    :param image_info: 包含图片路径和显示时间的列表，格式为 [(image_path, start_time, end_time), ...]
    :param output_path: 输出视频文件的路径
    """
    # 加载音频文件
    audio = AudioFileClip(audio_path)

    # 创建视频片段列表
    video_clips = []

    for img_path, start_time, end_time in image_info:
        # 加载图片
        img_clip = ImageClip(img_path).set_duration(end_time - start_time)
        # 设置图片在视频中的开始时间
        img_clip = img_clip.set_start(start_time)
        video_clips.append(img_clip)

    # 将所有视频片段合并
    final_clip = CompositeVideoClip(video_clips)

    # 设置视频的音频
    final_clip = final_clip.set_audio(audio)

    # 设置视频的总时长为音频的时长
    final_clip = final_clip.set_duration(audio.duration)

    # 写入视频文件
    final_clip.write_videofile(output_path, fps=24)



def get_song_info(song_id):
    # 获取音乐信息的API
    music_url = f'http://music.163.com/api/song/detail/?id={song_id}&ids=[{song_id}]'
    # 获取歌词的API
    lyric_url = f'http://music.163.com/api/song/lyric?os=pc&id={song_id}&lv=-1&kv=-1&tv=-1'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }

    try:
        # 获取音乐信息
        music_response = requests.get(music_url, headers=headers)
        music_data = json.loads(music_response.text)
        song_name = music_data['songs'][0]['name']

        # 获取歌词
        lyric_response = requests.get(lyric_url, headers=headers)
        lyric_data = json.loads(lyric_response.text)
        lyric = lyric_data.get('lrc', {}).get('lyric', '')

        return song_name, lyric

    except Exception as e:
        print(f"获取信息失败: {str(e)}")
        return None, None


def download_song(song_id):
    # 获取音乐文件的API
    download_url = f'http://music.163.com/song/media/outer/url?id={song_id}.mp3'
    song_name, lyric = get_song_info(song_id)

    if not song_name:
        return '','',''

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }

    try:
        # 下载MP3
        print(f"开始下载: {song_name}")
        response = requests.get(download_url, headers=headers)

        # 创建下载目录
        if not os.path.exists('downloads'):
            os.makedirs('downloads')

        # 保存MP3文件
        mp3_path = f'downloads/{song_name}.mp3'
        with open(mp3_path, 'wb') as f:
            f.write(response.content)
        print(f"MP3已保存: {mp3_path}")

        # 保存歌词文件
        if lyric:
            lrc_path = f'downloads/{song_name}.lrc'
            with open(lrc_path, 'w', encoding='utf-8') as f:
                f.write(lyric)
            print(f"歌词已保存: {lrc_path}")

    except Exception as e:
        print(f"下载失败: {str(e)}")
    return song_name,mp3_path,lrc_path
def get_song_id(url):
    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)
    return query_params.get('id', [None])[0]

if __name__ == '__main__':
    #https://music.163.com/song?id=409926&uct2=U2FsdGVkX1+5/x81TjmlmgOPp5zvVSP+NtLhsI6BG4w=
    song_id = '409926'  # 歌曲《叹》的ID
    #
    res  = download_song(song_id)
    print(res)
